import docker
from config.cluster_config_new import cluster_client


docker_client = docker.DockerClient(base_url="unix:///var/run/docker.sock")

def login_private_registry():
    if "harbor" not in cluster_client.cluster_config:
        return
    for item in cluster_client.cluster_config["harbor"]:
        print("login to {} username={} password={}".format(
            item["registry"], item["user"], item["password"]
        ))
        docker_client.login(username=item["user"],
                            password=item["password"],
                            registry=item["registry"])

def load_single_image(image_file):
    try:
        with open(image_file, "rb") as fd:
            print("open file {} successfully".format(image_file))
            return  docker_client.images.load(fd)[0]
    except Exception as err:
        print("load image from {} error: {}".format(image_file, str(err)))
        return None

def docker_tag_image(image_instance, tag):
    image_instance.tag(tag)

def load_and_tag_image(image_file, tag):
     image_instance = load_single_image(image_file)
     docker_tag_image(image_instance, tag)

def push_image(tag):
    return docker_client.images.push(tag, stream=True, decode=True)
